const AISuggestion = require('../models/AISuggestion');
const Category = require('../models/Category');
const db = require('../config/db');

class AIClassificationController {
  // Generate AI suggestion for a bill
  static async generateSuggestion(req, res) {
    try {
      const user_id = req.userId; // Set by auth middleware
      const bill_id = parseInt(req.params.billId);

      // Check if bill exists and belongs to user
      const billResult = await db.query(
        `SELECT * FROM bills WHERE id = $1 AND user_id = $2`,
        [bill_id, user_id]
      );

      if (billResult.rows.length === 0) {
        return res.status(404).json({ error: '账单未找到' });
      }

      const bill = billResult.rows[0];

      // Generate AI suggestion based on bill details
      const suggestion = AIClassificationController.generateAISuggestion(bill);

      // Save suggestion to database
      const result = await db.query(
        `INSERT INTO ai_suggestions (bill_id, suggested_category, confidence, explanation) 
         VALUES ($1, $2, $3, $4) RETURNING *`,
        [bill_id, suggestion.category, suggestion.confidence, suggestion.explanation]
      );

      const aiSuggestion = AISuggestion.fromRow(result.rows[0]);

      res.status(201).json({
        message: 'AI分类建议生成成功',
        suggestion: aiSuggestion.toJSON()
      });
    } catch (error) {
      console.error('Generate AI suggestion error:', error);
      res.status(500).json({ error: '内部服务器错误' });
    }
  }

  // Apply AI suggestion to a bill
  static async applySuggestion(req, res) {
    try {
      const user_id = req.userId; // Set by auth middleware
      const bill_id = parseInt(req.params.billId);
      const { suggestion_id } = req.body; // Get suggestion_id from request body

      // Check if bill exists and belongs to user
      const billResult = await db.query(
        `SELECT * FROM bills WHERE id = $1 AND user_id = $2`,
        [bill_id, user_id]
      );

      if (billResult.rows.length === 0) {
        return res.status(404).json({ error: '账单未找到' });
      }

      let suggestion;
      if (suggestion_id) {
        // Get specific AI suggestion by ID
        const suggestionResult = await db.query(
          `SELECT * FROM ai_suggestions WHERE id = $1 AND bill_id = $2`,
          [suggestion_id, bill_id]
        );

        if (suggestionResult.rows.length === 0) {
          return res.status(404).json({ error: '未找到AI分类建议' });
        }

        suggestion = suggestionResult.rows[0];
      } else {
        // Get the latest AI suggestion for this bill (backward compatibility)
        const suggestionResult = await db.query(
          `SELECT * FROM ai_suggestions WHERE bill_id = $1 ORDER BY created_at DESC LIMIT 1`,
          [bill_id]
        );

        if (suggestionResult.rows.length === 0) {
          return res.status(404).json({ error: '未找到AI分类建议' });
        }

        suggestion = suggestionResult.rows[0];
      }

      // Find the category by name
      const categoryResult = await db.query(
        `SELECT * FROM categories WHERE name = $1 AND (user_id = $2 OR user_id = 0)`,
        [suggestion.suggested_category, user_id]
      );

      if (categoryResult.rows.length === 0) {
        return res.status(404).json({ error: '建议的分类未找到' });
      }

      const category = categoryResult.rows[0];

      // Update bill with suggested category
      await db.query(
        `UPDATE bills SET category_id = $1 WHERE id = $2 AND user_id = $3`,
        [category.id, bill_id, user_id]
      );

      res.json({
        message: 'AI分类建议应用成功',
        updated_bill: {
          id: bill_id,
          category_id: category.id,
          category_name: category.name
        }
      });
    } catch (error) {
      console.error('Apply AI suggestion error:', error);
      res.status(500).json({ error: '内部服务器错误' });
    }
  }

  // Get AI suggestions for a bill
  static async getSuggestions(req, res) {
    try {
      const user_id = req.userId; // Set by auth middleware
      const bill_id = parseInt(req.params.billId);

      // Check if bill exists and belongs to user
      const billResult = await db.query(
        `SELECT * FROM bills WHERE id = $1 AND user_id = $2`,
        [bill_id, user_id]
      );

      if (billResult.rows.length === 0) {
        return res.status(404).json({ error: '账单未找到' });
      }

      // Get all AI suggestions for this bill
      const result = await db.query(
        `SELECT * FROM ai_suggestions WHERE bill_id = $1 ORDER BY created_at DESC`,
        [bill_id]
      );

      const suggestions = result.rows.map(row => AISuggestion.fromRow(row));

      res.json({
        suggestions: suggestions.map(suggestion => suggestion.toJSON())
      });
    } catch (error) {
      console.error('Get AI suggestions error:', error);
      res.status(500).json({ error: '内部服务器错误' });
    }
  }

  // Simple rule-based AI classification algorithm
  static generateAISuggestion(bill) {
    // In a real implementation, this would be a more sophisticated ML model
    // For now, we'll use a simple rule-based approach
    
    const title = bill.title.toLowerCase();
    const amount = parseFloat(bill.amount);
    
    // Define keywords for different categories
    const categoryKeywords = {
      '餐饮': ['餐厅', '咖啡', '快餐', '外卖', '吃饭', '午餐', '晚餐', '早餐', '美食', '饭店'],
      '交通': ['地铁', '公交', '出租车', '高铁', '机票', '油费', '停车费', '过路费', 'uber', '打车'],
      '购物': ['商场', '超市', '淘宝', '京东', '衣服', '鞋子', '电子产品', '化妆品', '购买'],
      '娱乐': ['电影', '游戏', 'KTV', '音乐会', '旅游', '度假', '门票', '游乐场'],
      '住房': ['房租', '水电费', '物业费', '装修', '家具', '房贷'],
      '医疗': ['医院', '药房', '药品', '体检', '治疗', '医生'],
      '教育': ['学费', '培训', '书籍', '课程', '学校', '学习'],
      '工资': ['工资', '薪水', '薪资'],
      '奖金': ['奖金', '提成', '奖励']
    };
    
    let bestMatch = null;
    let highestScore = 0;
    
    // Score each category based on keyword matches
    for (const [category, keywords] of Object.entries(categoryKeywords)) {
      let score = 0;
      
      // Check title for keywords
      for (const keyword of keywords) {
        if (title.includes(keyword)) {
          score += 1;
        }
      }
      
      // Adjust score based on amount for certain categories
      if (category === '工资' || category === '奖金') {
        // Income categories
        if (amount > 0) {
          score += 0.5;
        } else {
          score = 0; // Reset score if it's not income
        }
      } else {
        // Expense categories
        if (amount < 0) {
          score += 0.5;
        } else {
          score = 0; // Reset score if it's not expense
        }
      }
      
      if (score > highestScore) {
        highestScore = score;
        bestMatch = category;
      }
    }
    
    // Default categories if no good match found
    if (!bestMatch) {
      if (amount > 0) {
        bestMatch = '工资'; // Default income category
      } else {
        bestMatch = '餐饮'; // Default expense category
      }
    }
    
    // Determine confidence level
    let confidence = 'low';
    if (highestScore >= 2) {
      confidence = 'high';
    } else if (highestScore >= 1) {
      confidence = 'medium';
    }
    
    return {
      category: bestMatch,
      confidence: confidence,
      explanation: `基于账单标题"${bill.title}"和金额${bill.amount}，系统建议分类为${bestMatch}。`
    };
  }
}

module.exports = AIClassificationController;